<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/9/21 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%menu_role}}".
 *
 * @property int $id
 * @property string $role 角色名称
 * @property int $menu_id 菜单id
 * @property string $created_at
 */
class MenuRole extends BaseActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%menu_role}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['role', 'menu_id', 'created_at'], 'required'],
            [['menu_id'], 'integer'],
            [['created_at'], 'safe'],
            [['role'], 'string', 'max' => 64],
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMenu()
    {
        return $this->hasOne(Menu::class, ['id' => 'menu_id']);
    }

    /**
     * 获取角色已授权的全部菜单
     * @param string|array $roleName 角色名
     * @return MenuRole[]
     */
    public static function findAllByRole($roleName)
    {
        return static::find()
            ->where(['role' => $roleName])
            ->groupBy(['menu_id'])
            ->all();
    }

    /**
     * 获取角色已授权的全部菜单
     * @param $arr
     * @return array
     */
    public static function findAllByRoleWithMenu($arr)
    {
        return static::find()->where(['role' => $arr])
            ->joinWith(['menu'])
            ->groupBy(['menu_id'])
            ->all();
    }

    /**
     * 删除角色全部授权的菜单
     * @param $roleName
     * @return int
     */
    public static function removeRole($roleName)
    {
        try {
            Yii::$app->getDb()->createCommand()
                ->delete(static::tableName(), ['role' => $roleName])
                ->execute();
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}
